<template>
  <div>
    <div class="top" id="top" @click="backTop()" v-show="showToTop">
      <img src="@/assets/images/Common/top.jpg" />
    </div>
  </div>
</template>
<script>
// import {
//   requestAnimationFrame,
//   cancelAnimationFrame
// } from '@/components/common/AnimationFrame/AnimationFrame.js'

export default {
  data() {
    return {
      // 滚动条的高度
      scrollTop: 0,
      showToTop: false
    }
  },
  watch: {
    scrollTop(val) {
      if (this.scrollTop >= 200) {
        this.showToTop = true
      } else {
        this.showToTop = false
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
  },
  destroyed() {
    // 离开该页面需要移除这个监听的事件，不然会报错
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 保存滚动值，这是兼容的写法
    handleScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      if (this.scrollTop >= 200) {
        this.showToTop = true
      }
    },

    // 滚动条回到顶部
    backTop() {
      let timer = null
      const _that = this
      cancelAnimationFrame(timer)
      timer = requestAnimationFrame(function fn() {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 100
          document.body.scrollTop = document.documentElement.scrollTop =
            _that.scrollTop
          timer = requestAnimationFrame(fn)
        } else {
          cancelAnimationFrame(timer)
          _that.showToTop = false
        }
      })
    }
  }
}
</script>
<style scoped>
.content .top {
  position: fixed;
  right: 20px;
  bottom: 100px;
}
.content .top img {
  width: 60px;
  height: 60px;
}
</style>
